﻿(function ($) {

    //models
    window.Comment = Backbone.Model.extend({
        url: function () {
            return "/Posts/" + $("#slug").val() + "/Comment";
        }
    });

    window.Comments = Backbone.Collection.extend({
        model: Comment,
    });
    
    window.Post = Backbone.Model.extend({
        url: function () {
            return "/Posts/" + this.attributes.slug;
        },
        initialize: function () {
            var self = this;
            this.comments = new Comments(this.get("Comments"));            
        }
    });

    //collections
    window.Posts = Backbone.Collection.extend({
        model: Post,
        url: "/Posts"
    });

    window.RecentPosts = Backbone.Collection.extend({
        model: Post,
        url: "/RecentPosts"
    });

    //a global reference to the collection
    window.posts = new Posts();
    window.recentPosts = new RecentPosts();

    $(document).ready(function () {
        //Views
        window.PostFormView = Backbone.View.extend({
            template: _.template($("#post-form-template").html()),
            initialize: function () {
                _.bindAll(this, 'render');                
            },
            render: function () {
                $(this.el).html(this.template(this.model.toJSON()));
                return this;
            }
        });

        window.PostView = Backbone.View.extend({
            template: _.template($("#post-template").html()),
            initialize: function () {
                _.bindAll(this, 'render', 'updateModel');
                this.model.comments.bind('add', this.updateModel);
            },

            render: function () {
                var $comments,
                    commentFormView,
                    collection = this.comments;
                
                $(this.el).html(this.template(this.model.toJSON()));
                $comments = this.$('.comments');

                this.comments = new Comments(this.model.get("Comments"));

                this.comments.each(function (comment) {
                    var view = new CommentItemView({
                        model: comment,
                        collection: collection
                    });
                    $comments.append(view.render().el);
                });

                commentFormView = new CommentFormView({
                    model: this.model,
                    slug: this.model.get("slug")
                });

                $comments.after(commentFormView.render().el);
                return this;
            },

            updateModel: function(){
                var self = this;
                this.model.fetch({success: function(){
                        self.render();
                    }
                });
            }
        });

        window.CommentItemView = Backbone.View.extend({
            template: _.template($("#comment-item-template").html()),
            tagName: "li",
            initialize: function () {
                _.bindAll(this, 'render');
            },

            render: function () {
                $(this.el).html(this.template(this.model.toJSON()));
                return this;
            }
        });

        window.PostItemView = Backbone.View.extend({
            template: _.template($("#post-item-template").html()),
            tagName: "article",
            initialize: function () {
                _.bindAll(this, 'render');
            },

            render: function () {
                $(this.el).html(this.template(this.model.toJSON()));
                return this;
            }
        });

        window.RecentPostView = PostItemView.extend({
            template: _.template($("#recent-post-template").html()),
            tagName: "li"
        });

        window.PostsView = Backbone.View.extend({
            template: _.template($("#posts-template").html()),
            initialize: function () {
                _.bindAll(this, 'render');
                this.collection.bind('reset', this.render);
            },

            render: function () {
                var $posts,
					collection = this.collection;

                $(this.el).html(this.template({}));
                $posts = this.$(".posts");
                this.collection.each(function (post) {
                    var view = new PostItemView({
                        model: post,
                        collection: collection
                    });
                    $posts.append(view.render().el);
                });

                return this;
            }
        });

        window.RecentPostsView = PostsView.extend({
            template: _.template($("#recent-posts-template").html()),
            className: "side_element",
            render: function () {
                var $posts,
					collection = this.collection;

                $(this.el).html(this.template({}));
                $posts = this.$(".recent");
                this.collection.each(function (post) {
                    var view = new RecentPostView({
                        model: post,
                        collection: collection
                    });
                    $posts.append(view.render().el);
                });

                return this;
            }
        });

        window.TagCloudView = Backbone.View.extend({
            template: _.template($("#tag-cloud-template").html()),
            className: "side_element",
            initialize: function () {
                _.bindAll(this, 'render');
            },
            render: function () {
                $(this.el).html(this.template({}));
                return this;
            }
        });

        window.CommentFormView = Backbone.View.extend({
            template: _.template($("#comment-form-template").html()),
            events: {
                "submit .add_comment": "save"
            },
            initialize: function () {
                _.bindAll(this,
                'render',
                'save');

            },
            render: function () {
                $(this.el).html(this.template({}));
                return this;
            },
            save: function () {

                var $form = this.$(".add_comment");
                var attrs = $form.serializeObject();
                var model = this.model;
                var comments = model.comments;
                var comment = new Comment();
                comment.save(attrs, {
                    success: function () {
                        $form[0].reset();
                    },
                    error: function () {
                        alert("Inferno!");
                    }
                });

                comments.add(comment);
                
                return false;
            }
        });

        //create the router...
        window.XangoBlog = Backbone.Router.extend({
            routes: {
                "": "defaultAction",
                "Posts/New": "newPost",
                "Posts/:id": "showPost",
                
            },

            initialize: function () {
                this.postsView = new PostsView({
                    collection: window.posts
                });
                this.recentPostsView = new RecentPostsView({
                    collection: window.recentPosts
                });
                //TODO: Create tags model and collection and populate the view.
                this.tagCloudView = new TagCloudView();
            },

            defaultAction: function () {
                $('#content').empty();
                $("#content").append(this.postsView.render().el);
                this.loadRightPane();
            },

            showPost: function (id) {
                this.post = new Post({ slug: id });
                this.post.fetch({
                    success: function (model, resp) {
                        var view = new PostView({ model: model });
                        $("#content").empty();
                        $(view.render().el).hide().appendTo("#content").fadeIn(1000);
                    }
                });
                this.loadRightPane();
            },

            newPost: function(){
                post = new Post();
                var view = new PostFormView({ model: post });
                $("#content").empty();
                $(view.render().el).hide().appendTo("#content").fadeIn(1000);
                this.loadRightPane();
            },

            loadRightPane: function () {
                $("#right_panel").empty();
                $("#right_panel").append(this.recentPostsView.render().el);
                $("#right_panel").append(this.tagCloudView.render().el);
            }
        });

        // Kick off the application
        window.App = new XangoBlog();
        Backbone.history.start({
            pushState: false
        });
    });
})(jQuery);